package com.gitee.chili.leisure.message;

import com.gitee.chili.leisure.ResponseCode;
import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.core.AbstractDefaultMessage;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.game.MahjongPlayer;
import com.gitee.chili.leisure.game.RoomDetail;
import com.gitee.chili.leisure.model.MahjongModel;
import com.gitee.chili.leisure.model.MessageCmdEnum;
import com.gitee.chili.leisure.util.AuxiliaryChannel;
import com.gitee.chili.leisure.util.AuxiliaryRoom;
import com.google.common.collect.Maps;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * ReadyHand
 *
 * @author week solider
 * @since 2020.09.22
 */
@Slf4j
public class ReadyHand extends AbstractDefaultMessage {

    private int discard;

    public ReadyHand(Packet packet, Channel channel) {
        super(packet, channel);
    }

    @Override
    protected void decoder(byte[] body) throws InvalidProtocolBufferException {
        MahjongModel.ReadyHandCmd readyHand = MahjongModel.ReadyHandCmd.parseFrom(body);
        discard = readyHand.getDiscard();
    }

    @Override
    public Packet parseBody() {
        RoomDetail roomDetail = RoomManager.obtain(getRoomNum());

        MahjongPlayer player = (MahjongPlayer) roomDetail.obtain(getMemberId());

        if (player.getHandsCards().contains(discard) && AuxiliaryRoom.isReadyHand(player, discard)) {

            // 统计所有听牌及番数
            List<MahjongModel.ReadyHandTipsResult.Tips> tbs = new ArrayList<>();
            player.getReadyHandMap().forEach((k, v) -> {
                MahjongModel.ReadyHandTipsResult.Tips tips = MahjongModel.ReadyHandTipsResult.Tips.newBuilder()
                        .setReadyHand(k)
                        .setPoints(v)
                        .build();
                tbs.add(tips);
            });

            // 清空记录
            player.setReadyHandMap(Maps.newHashMap());

            MahjongModel.ReadyHandTipsResult.Builder builder = MahjongModel.ReadyHandTipsResult.newBuilder();
            builder.addAllTips(tbs);
            return Packet.newPacket(MessageCmdEnum.Command.READY_HAND_TIPS, builder.build().toByteArray());
        }

        // 错误信息提示
        AuxiliaryChannel.errorMessage(getChannel(), getCommand(), ResponseCode.NOT_FOUND_CARDS);

        return null;
    }
}
